<?php

declare(strict_types=1);

namespace app\api\command\v1;

use app\api\model\v1\EveryDayAnswerCensus;
use app\api\model\v1\TopicUserDay;
use app\api\model\v1\TopicUserDaySync;
use app\api\model\v1\Unit;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\facade\Db;

class syncTopicUserDay extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('sync_topic')
            ->setDescription('the sync_topic command');
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/6/10 11:12
     * @param Input $input
     * @param Output $output
     * @return int|void|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 同步每日答题的数据 2 个小时同步一次
     */
    protected function execute(Input $input, Output $output)
    {
        $dateWhere[] = array('date_of', '=', date("Y-m-d"));
        //$dateWhere[] = array('date_of', '=', '2022-05-14');
        $subQuery = Db::table('topic_user_day')
            // ->whereDay('create_time', date("Y-m-d"))
            ->where($dateWhere)
            ->where('is_admin', 0) //不为管理员的时候
            ->where('is_sync', 0)
            ->order('error asc')
            ->limit(1000000)
            ->buildSql();
        $res = Db::table($subQuery . ' a')
            ->group('a.user_id')
            ->order('a.id desc')
            ->select()->toArray();
        if (!empty($res)) {
            foreach ($res as $key => $v) {

                $output->writeln(sprintf('Synchronize data with ID - ' . $v['id'] . '-' . $v['date_of']));
                try {
                    $unit = Unit::withCount(['users' => function ($query) {
                        $query->where('wx_role_id', 3);
                        return $query;
                    }])->withCount(['users' => function ($query, &$alias) {
                        $query->where('wx_role_id', 4);
                        $alias = 'card_count';
                        return $query;
                    }])->find($v['unit_id']);
                    $is_find = EveryDayAnswerCensus::where(['unit_id' => $v['unit_id'], 'date_of' => $v['date_of']])->find();
                    if (is_null($is_find)) {
                        EveryDayAnswerCensus::create([
                            'unit_id' => $v['unit_id'],
                            'date_of' => $v['date_of'],
                            'completed_number' => 1,
                            'unit_number' => ($unit['users_count'] + $unit['card_count']) ?? 0,
                            'user_ids' => $v['user_id']
                        ]);
                    } else {
                        if ($is_find['completed_number'] !=  $unit['users_count']) {
                            if (strpos($is_find['user_ids'], $v['user_id']) === false) {
                                $is_find->save([
                                    'completed_number' => $is_find['completed_number'] + 1,
                                    'user_ids' => $is_find['user_ids'] . ',' . $v['user_id']
                                ]);
                            }else{
                                $is_find->save([
                                    'completed_number' => $is_find['completed_number'] + 1,
                                    'user_ids' => $v['user_id']
                                ]);
                            }
                        }
                    }
                    $is_f = TopicUserDaySync::where(['unit_id' => $v['unit_id'], 'user_id' => $v['user_id'], 'date_of' => $v['date_of']])->find();
                    if (is_null($is_f)) {
                        // 把记录存放在同步表中！
                        $res_sync = TopicUserDaySync::create([
                            'user_id' => $v['user_id'],
                            'unit_id' => $v['unit_id'],
                            'date_of' => $v['date_of'],
                            'correct' => $v['correct'],
                            'error' => $v['error'],
                            'correct_rate' => $v['correct_rate'],
                            'duration' => $v['duration'],
                            'total_seconds' => $v['total_seconds'],
                            'score' => $v['score'],
                            'status' => $v['status'],
                            'is_admin' => $v['is_admin'],
                            'topic_user_day_id' => $v['id'],
                        ])->id;
                        // if ($res_sync){
                        //     // TopicUserDay::update([
                        //     //     'id'=>$v['id'],
                        //     //     'is_sync'=>1
                        //     // ]);

                        //     TopicUserDay::where('user_id',$v['user_id'])->where('unit_id',$v['unit_id'])->where('date_of', date("Y-m-d"))->update([
                        //         'is_sync'=>1
                        //     ]);
                        // }
                    } else {
                        if (intval($v['score']) > intval($is_f['score'])) {
                            $is_f->save([
                                'user_id' => $v['user_id'],
                                'unit_id' => $v['unit_id'],
                                'date_of' => $v['date_of'],
                                'correct' => $v['correct'],
                                'error' => $v['error'],
                                'correct_rate' => $v['correct_rate'],
                                'duration' => $v['duration'],
                                'total_seconds' => $v['total_seconds'],
                                'score' => $v['score'],
                                'status' => $v['status'],
                                'is_admin' => $v['is_admin'],
                                'topic_user_day_id' => $v['id'],
                            ]);

                            //                             //变更最新的同步数据
                            //                             // TopicUserDay::update([
                            //                             //     'id'=>$v['id'],
                            //                             //     'is_sync'=>1
                            //                             // ]);
                            //                             TopicUserDay::where('user_id',$v['user_id'])->where('unit_id',$v['unit_id'])->where('date_of', date("Y-m-d"))->update([
                            //                                 'is_sync'=>1
                            //                             ]);
                            // //                            //把原有的值状态更新掉
                            // //                            TopicUserDay::update([
                            // //                                'id'=>$is_f['topic_user_day_id'],
                            // //                                'is_sync'=>0
                            // //                            ]);
                        }
                    }
                } catch (\Exception $exception) {
                    $output->writeln($exception->getMessage());
                }
                TopicUserDay::where('user_id', $v['user_id'])->where('unit_id', $v['unit_id'])->where('date_of', date("Y-m-d"))->update([
                    'is_sync' => 1
                ]);
            }
            sleep(3); //睡眠1秒
        }
        $output->writeln('Synchronize data complete');
    }
}
